<template>
  <div>
    <el-table v-loading="loading" :data="dataList" table-layout="fixed" :height="height" border ref="userTableRef"
      @cell-click="distribution">
      <el-table-column label="采样员" align="center" prop="cyUserName" fixed="left" width="90px"
        v-if="dataList.length > 0" />
      <el-table-column v-for="(month, index1) in monthArray" :key="index1" :label="month" align="center">
        <template #header>
          <el-row>
            <el-col :span="8">
              <el-icon v-if="!index1" @click="linkWeek('previous')" style="cursor: pointer;color: #2c9e3d;">
                <ArrowLeftBold />
              </el-icon>
            </el-col>
            <el-col :span="8">
              {{ month }}
            </el-col>
            <el-col :span="8">
              <el-icon v-if="index1" @click="linkWeek('next')" style="cursor: pointer;color: #2c9e3d">
                <ArrowRightBold />
              </el-icon>
            </el-col>
          </el-row>
        </template>
        <template v-for="(weekItem, index) in weekList">
          <el-table-column :key="index" v-if="index1 == 0 ? index <= 6 : index > 6" align="center"
            :prop="weekItem.weekDate">
            <template #header>
              <span :style="index == 5 || index == 6 || index == 12 || index == 13 ? 'color: #12be80;' : ''">{{
                parseInt(weekItem.day) + ' ' + weekItem.week }}</span>
            </template>
            <template #default="scope">
              <template v-if="scope.row[weekItem.weekDate]">
                <div>{{ "方案数：" + scope.row[weekItem.weekDate][0] }}</div>
                <div>{{ "点位数：" + scope.row[weekItem.weekDate][1] }}</div>
              </template>
              <template v-else>
                <div>方案数：0</div>
                <div>点位数：0</div>
              </template>
            </template>
          </el-table-column>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :class="'el-dialog-theme3'" v-model="open" :title="title" append-to-body draggable
      :close-on-click-modal="false" @close="closedDialog" width="1200">
      <el-form label-width="110px" :model="form" ref="dialogFormRef" :rules="rules">
        <el-row>
          <el-col :span="7">
            <el-form-item label="计划日期：">{{
              parseTime(form.cyDate, "{y}年{m}月{d}日")
            }}</el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="采样人员：">{{
              form.cyUserName
            }}</el-form-item>
          </el-col>
          <el-col :span="7">
            <el-button link type="success" style="line-height: 2">导出采样任务单</el-button>
          </el-col>
        </el-row>
        <p class="pinformation">搜索条件</p>
        <el-form :model="searchCriteriaForm">
          <el-row :gutter="10">
            <el-col :span="7">
              <el-form-item label="点位编号：">
                <el-input v-model="searchCriteriaForm['project.projectCode']" clearable placeholder="请输入点位编号"
                  @keyup.enter="search"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item label="点位名称：">
                <el-input v-model="searchCriteriaForm['point.pointName']" clearable placeholder="请输入点位名称"
                  @keyup.enter="search"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="第几天：">
                <el-input v-model="searchCriteriaForm.currentDay" clearable placeholder="请输入第几天"
                  @keyup.enter="search"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-row justify="end">
                <el-button type="success" @click="search">搜索</el-button>
                <el-button class="business resetBtn" @click="resetForm">重置</el-button>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
        <el-row>
          <p class="pinformation">当日点位列表</p>
          <p class="totalStyle">共 {{ currentDayPointList.length }} 条数据</p>
        </el-row>
        <el-table :data="currentDayPointList" max-height="15vw" @selection-change="onAddSelect" ref="currentDayPointRef"
          row-key="cyId">
          <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
          <el-table-column prop="project.projectCode" label="方案编号" align="center" width="120" show-overflow-tooltip />
          <el-table-column prop="project.wtCustomName" label="委托单位" align="center" show-overflow-tooltip />
          <el-table-column prop="point.pointName" label="点位名称" align="center" width="150" show-overflow-tooltip />
          <el-table-column prop="jclbId" label="检测类型" align="center" width="130" show-overflow-tooltip>
            <template #default="scope">
              {{
                proxy.getItemByArray(
                  jclbList,
                  "jclbId",
                  scope.row.jclbId,
                  "jclbName"
                )
              }}
            </template>
          </el-table-column>
          <el-table-column prop="sumDay" label="连测天数" align="center" width="90" />
          <el-table-column prop="currentDay" label="第几天" align="center" width="80" />
          <el-table-column prop="cyDate" label="计划日期" align="center" width="100" />
          <el-table-column prop="fpcyy" label="分配采样员" align="center" show-overflow-tooltip />
        </el-table>
        <el-row style="margin-top: 10px">
          <el-col :span="8">
            <el-form-item label="调整日期：" prop="sengTime">
              <el-date-picker v-model="form.sengTime" value-format="YYYY-MM-DD" :clearable="false" :editable="false"
                :picker-options="false" placeholder="调整日期" @change="sengTimeChange"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label-width="0">
              {{
                "当日已安排" +
                countForm.projectCount +
                "个方案，" +
                countForm.pointCount +
                "个点位"
              }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item label="选择采样员：" prop="cyUserIds">
              <el-select v-model="form.cyUserIds" multiple filterable :disabled="!form.sengTime" style="width: 100%">
                <el-option v-for="item in cyUserList" :key="item.userId" :value="item.userId" :label="item.nickName">
                  <span style="float: left; margin-right: 20px">{{
                    item.nickName
                  }}</span>
                  <span style="float: right">{{ item.remark }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2" :offset="1">
            <el-button type="success" @click="define">确定</el-button>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="open = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getNextDays } from "@/api/common";
import { allListJclb } from "@/api/store/jclb";
import {
  getDialogListByUser,
  userView,
  getDialogUserList,
  getDialogCount,
  putDialogDate,
} from "@/api/project/projectPlan";

const { proxy } = getCurrentInstance();
const weekList = ref([]);
const dataList = ref([]);
const loading = ref(false);
const props = defineProps({
  queryParams: {
    type: Object,
  },
});
const monthArray = ref([]);
const open = ref(false);
const title = ref("调整日期");
const form = ref({
  cyIds: [],
});
const searchCriteriaForm = ref({
  cyUserIds: [],
});
const currentDayPointList = ref([]);
const rules = ref({
  sengTime: [{ required: true, message: "调整日期不能为空", trigger: "blur" }],
  cyUserIds: [
    { required: true, message: "分配采样员不能为空", trigger: "blur" },
  ],
});

const jclbList = ref([]);
allListJclb().then((res) => {
  jclbList.value = res.data;
});

function getUserList() {
  getUserView();
}

defineExpose({
  getUserView,
});

function getUserView(day1) {
  let temp = props.queryParams
  temp.params.queryDate = day1 ? day1 : day.value
  userView(temp).then(
    (res) => {
      if (!res.data) return;
      weekList.value = res.data.weekList;
      dataList.value = res.data.dataList;
      monthArray.value = res.data.monthList;
    }
  );
}

function formatCell(content) {
  if (!content) return "";
  return "方案：" + content[0] + " 点位：" + content[1];
}

function distribution(row, column, cell, event) {
  let isReturn = false
  for (const key in row) {
    if (key === column.property) {
      isReturn = true
      break
    }
  }
  if (!isReturn) return
  open.value = true;
  form.value.cyDate = column.property;
  form.value.sengTime = proxy.parseTime(column.property, "{yyyy}-{mm}-{dd}");
  sengTimeChange();
  form.value.cyUserName = row.cyUserName;
  searchCriteriaForm.value.cyUserIds = [row.cyUserId];
  search().then((res) => {
    proxy.$refs["currentDayPointRef"].clearSelection();
    proxy.$refs["currentDayPointRef"].toggleAllSelection();
  });
}

const day = ref("");
function getQueryDate() {
  getNextDays().then((res) => {
    day.value = res.data;
    getUserList();
  });
}

function closedDialog() {
  searchCriteriaForm.value = {
    cyUserIds: [],
  };
  form.value = { cyIds: [] };
  currentDayPointList.value = [];
}

function onAddSelect(selection) {
  form.value.cyIds = selection.map((item) => {
    return item.cyId;
  });
  var previous = "";
  for (let i = 0; i < selection.length; i++) {
    let temp = "";
    let tempcyUserNames = selection[i].taskUserList.map((item1) => {
      return item1.cyUserName;
    });
    let tempUserIds = selection[i].taskUserList.map((item1) => {
      return item1.cyUserId;
    });
    temp = tempcyUserNames.join("、");
    if (previous == "") {
      previous = temp;
    }
    if (temp !== previous) {
      form.value.cyUserIds = [];
      break;
    } else {
      form.value.cyUserIds = tempUserIds;
    }
  }
  if (!selection.length) {
    form.value.cyUserIds = [];
  }
}

function search() {
  return new Promise((resolve, reject) => {
    searchCriteriaForm.value.cyDate = proxy.parseTime(
      form.value.cyDate,
      "{y}-{m}-{d}"
    );
    getDialogListByUser(searchCriteriaForm.value).then((res) => {
      currentDayPointList.value = res.data;
      currentDayPointList.value.forEach((item, index) => {
        var temp = item.taskUserList.map((row) => {
          return row.cyUserName;
        });
        currentDayPointList.value[index].fpcyy = temp.join("、");
      });
      resolve();
    });
  });
}

const countForm = ref({ projectCount: 0, pointCount: 0 });
function sengTimeChange() {
  cyUserList.value = [];
  countForm.value = { projectCount: 0, pointCount: 0 };
  getDialogUserList(form.value.sengTime).then((res) => {
    cyUserList.value = res.data;
  });
  getDialogCount(form.value.sengTime).then((res) => {
    countForm.value = res.data;
  });
}
const cyUserList = ref([]);

function define() {
  if (form.value.cyUserIds.length == 1) {
    proxy.$modal.msgError("至少选择2个采样员！");
    return;
  }
  if (form.value.cyIds.length > 1) {
    proxy.$refs["dialogFormRef"].validate(async (valid) => {
      if (valid) {
        var temp = {
          cyDate: form.value.sengTime,
          cyUserIds: form.value.cyUserIds,
          cyIds: form.value.cyIds,
        };
        putDialogDate(temp).then((res) => {
          proxy.$modal.msgSuccess(res.msg);
          search().then((res) => {
            proxy.$refs["currentDayPointRef"].clearSelection();
            proxy.$refs["currentDayPointRef"].toggleAllSelection();
          });
          getQueryDate();
          getUserList();
        });
      }
    });
  } else {
    proxy.$modal.msgError("选择要分配的检测点位！");
  }
}

function resetForm() {
  searchCriteriaForm.value = {
    cyUserIds: searchCriteriaForm.value.cyUserIds,
  };
  search();
}

const height = ref();

function getTableHeight() {
  nextTick(() => {
    height.value = proxy.getSubFileHeight(proxy, "userTableRef");
  });
}

function linkWeek(row) {
  var Time = new Date(weekList.value[0].weekDate);
  let weekNum = Time.getDay();
  weekNum = weekNum == 0 ? 7 : weekNum;
  let fitstDate = new Date(
    Time.getTime() - (weekNum + 6) * 24 * 60 * 60 * 1000
  );
  let lastDate = new Date(
    Time.getTime() + (7 - weekNum + 7) * 24 * 60 * 60 * 1000
  );
  let startDate;
  if (row == "previous") {
    startDate = `${fitstDate.getFullYear()}-${fitstDate.getMonth() + 1 < 10
      ? "0" + (fitstDate.getMonth() + 1)
      : fitstDate.getMonth() + 1
      }-${fitstDate.getDate() < 10 ? "0" + fitstDate.getDate() : fitstDate.getDate()
      }`;
  } else {
    startDate = `${lastDate.getFullYear()}-${lastDate.getMonth() + 1 < 10
      ? "0" + (lastDate.getMonth() + 1)
      : lastDate.getMonth() + 1
      }-${lastDate.getDate() < 10 ? "0" + lastDate.getDate() : lastDate.getDate()
      }`;
  }
  getUserView(startDate);
}
onMounted(() => {
  nextTick(() => {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  })
})
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});
getQueryDate();
</script>
